package com.like.hospitalworld;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.like.entity.AppStartReq;
import com.like.entity.Department;
import com.like.entity.GeneralResponse;
import com.like.entity.GetDepReq;
import com.like.entity.GetDepResp;
import com.like.entity.OpenTokenReq;
import com.like.entity.OpenTokenResp;
import com.like.likeutils.network.RetrofitCallback;
import com.like.network.AuthService;
import com.like.network.RetrofitUtil;
import com.like.network.UserService;
import com.like.utils.AppUtils;
import com.like.utils.Constants;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

@ContentView(R.layout.activity_welcome)
public class WelcomeActivity extends GPSBaseActivity implements BDLocationListener {

    @ViewInject(R.id.countdown)
    private TextView mCountDown;
    private int mCountDownNumber = 6;
    private AuthService mAuthService;
    private UserService mUserService;
    private Handler mHandler;
    private Department mRootDep;
    private int mAllDepCounts = 0;
    private int mCurrentDepCount = 0;
    private Runnable mCountDownRunnable = new Runnable() {
        @Override
        public void run() {
            mCountDownNumber -= 1;
            if (mCountDownNumber <= 0)
                toNextActivity();
            else {
                mCountDown.setText("跳过" + mCountDownNumber + "s");
                mHandler.postDelayed(mCountDownRunnable, 1000);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRootDep = new Department();
        mHandler = new Handler();
        mHandler.postDelayed(mCountDownRunnable, 1000);
        mAuthService = RetrofitUtil.getService(AuthService.class);
        mUserService = RetrofitUtil.getService(UserService.class);
        getToken();
    }

    private void getLocation() {
        initLocation(this);
        startLocate();
    }

    private void appStart(double latitude, double longitude) {
        Call<GeneralResponse<String>> call = mAuthService.appStart(Constants.getGUID(), Constants.APP_SECRET, AppUtils.getAppModel(), latitude + "#" + longitude, AppUtils.getVersion(m.mContext));
        call.enqueue(new RetrofitCallback<GeneralResponse<String>>());
    }

    private void getToken() {
        OpenTokenReq req = new OpenTokenReq(Constants.PID, Constants.PROJECT_ID, AppUtils.getDeviceId(m.mContext));
        Call<GeneralResponse<OpenTokenResp>> call = mAuthService.openToken(Constants.PID, Constants.PROJECT_ID, req);
        call.enqueue(new RetrofitCallback<GeneralResponse<OpenTokenResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<OpenTokenResp>> call, Response<GeneralResponse<OpenTokenResp>> response) {
                if (!response.isSuccessful())
                    return;
                String token = response.body().data.token;
                m.setToken(token);
                getLocation();
                getAllDepartments();
            }

            @Override
            public void onFailure(Call<GeneralResponse<OpenTokenResp>> call, Throwable t) {
            }
        });
    }

    private void getAllDepartments() {
        if (m.getAllDeps() != null && m.getAllDeps().size() > 0)
            return;
        GetDepReq req = new GetDepReq(GetDepReq.DEP_ALL);
        Call<GeneralResponse<GetDepResp>> call = mUserService.getDepartmentList(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<GetDepResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<GetDepResp>> call, Response<GeneralResponse<GetDepResp>> response) {
                if (!response.isSuccessful())
                    return;
                GeneralResponse<GetDepResp> resp = response.body();
                GetDepResp getDepResp = resp.data;
                List<Department> deps = getDepResp.departments;
                mAllDepCounts = deps.size();
                getDepartments(GetDepReq.DEP_MAIN, mRootDep);
            }

            @Override
            public void onFailure(Call<GeneralResponse<GetDepResp>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void getDepartments(int depId, final Department parentDep) {
        GetDepReq req = new GetDepReq(depId);
        Call<GeneralResponse<GetDepResp>> call = mUserService.getDepartmentList(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<GetDepResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<GetDepResp>> call, Response<GeneralResponse<GetDepResp>> response) {
                if (!response.isSuccessful())
                    return;
                GeneralResponse<GetDepResp> resp = response.body();
                GetDepResp getDepResp = resp.data;
                List<Department> deps = getDepResp.departments;
                mCurrentDepCount += deps.size();
                parentDep.subDeps = deps;
                for (Department dep : deps)
                    getDepartments(dep.id, dep);
                if (mCurrentDepCount == mAllDepCounts) {
                    m.setAllDeps(mRootDep.subDeps);
                }
            }

            @Override
            public void onFailure(Call<GeneralResponse<GetDepResp>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Event(R.id.countdown)
    private void countdownClick(View v) {
        mHandler.removeCallbacks(mCountDownRunnable);
        toNextActivity();
    }

    private void toNextActivity() {
        Intent intent = null;
        if (m.isFirstRun())
            intent = new Intent(m.mContext, GuideActivity.class);
        else if (m.getLoginResp() == null)
            intent = new Intent(m.mContext, LoginActivity.class);
        else
            intent = new Intent(m.mContext, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        double longitude = bdLocation.getLongitude();
        double latitude = bdLocation.getLatitude();
        m.setLongitude(longitude);
        m.setLatitude(latitude);
        appStart(latitude, longitude);
        stopLocate();
    }
}
